#-*-coding:utf-8-*-
import os
import time
import shutil
import pymysql
from app.static.interface_auto.common import HttpUntil
from app.static.interface_auto.common import common
from app.database_config import *
from common.readSql import SQL

#删除原有文件夹
def init_task_dir(taskId):
    task_dir = 'app/static/interface_auto/test_src/' + str(taskId)
    print (task_dir)
    if os.path.exists(task_dir):
        print ('test')
        delList = []
        delDir = task_dir
        delList = os.listdir(delDir)
        if len(delList) > 0:
            for f in delList:
                filePath = os.path.join(delDir, f)
                if os.path.isfile(filePath):
                    os.remove(filePath)
                    common.logInfo( filePath + " was removed!")
                elif os.path.isdir(filePath):
                    shutil.rmtree(filePath, True)
                common.logInfo("Directory: " + filePath + " was removed!")
        os.rmdir(task_dir)
        common.logInfo("Directory: " + task_dir + " was removed!")
    else:
        common.logInfo( 'have no dir:'+ task_dir)

def doSth(taskId):
    init_task_dir(taskId)
    # 开始生成脚本
    url = 'http://127.0.0.1:5000/build'
    values = {
        "entry": taskId,
    }
    (responsedata,code) = HttpUntil.post(url, values, '')
    if responsedata:
        if responsedata['code'] == 0:
            common.logInfo( 'run and build settime task:'+str(taskId))
    else:
        common.logInfo('can not connect to the server , please check if it has been runned')
    time.sleep(60)

def create_tables(dbc):
    file_url = os.path.join(os.path.dirname(os.path.abspath(__file__)), "tables.sql")
    print(file_url)
    with open(file_url, "r") as f:
        all_lines = f.readlines()
        start = 0
        for line in all_lines:
            if line.strip().endswith(";"):
                sql = ("".join(all_lines[start:all_lines.index(line)+1]))
                start = all_lines.index(line)+1
                dbc.execute(sql)

def main():
    print ('listen run start')
    if "interface_task_list" not in SQL.show_tables():
        SQL.create_table(os.path.join(os.path.dirname(os.path.abspath(__file__)), "tables.sql"))
    while True:
        while True:
            try:
                task_list = SQL.get_all_task()
            except:
                common.logInfo("lost mysql connect!")
                time.sleep(60)
                continue
            task_data= []
            for obj in task_list:
                taskId = obj[0]
                start_time = obj[8]
                task_data.append([taskId,start_time])
            logtime = time.strftime('%H:%M', time.localtime(time.time()))
            print (task_data,logtime)
            for item in task_data:
                print(item[1], str(logtime))
                if item[1] == str(logtime):
                    doSth(item[0])
                    break
            time.sleep(60)


start_listen = main